/**
 * @file initData.js
 * @description 初始化本地存储中的示例数据
 */

// 初始化角色数据
export const initRoles = () => {
  const existingRoles = localStorage.getItem('roles');
  
  if (!existingRoles) {
    const defaultRoles = [
      {
        id: 1,
        name: '超级管理员',
        description: '拥有系统所有权限',
        permissions: ['all'],
        createdAt: new Date().toISOString(),
      },
      {
        id: 2,
        name: '订单管理员',
        description: '负责订单处理和发货',
        permissions: ['dashboard', 'orders', 'view_orders', 'edit_orders'],
        createdAt: new Date().toISOString(),
      },
      {
        id: 3,
        name: '用户管理员',
        description: '负责用户管理',
        permissions: ['dashboard', 'users', 'view_users', 'edit_users'],
        createdAt: new Date().toISOString(),
      },
    ];
    
    localStorage.setItem('roles', JSON.stringify(defaultRoles));
    return defaultRoles;
  }
  
  return JSON.parse(existingRoles);
};

// 初始化管理员用户数据
export const initAdminUsers = () => {
  const existingAdmins = localStorage.getItem('adminUsers');
  
  if (!existingAdmins) {
    const defaultAdmins = [
      {
        id: 1,
        username: 'admin',
        password: 'admin123',
        name: '系统管理员',
        email: 'admin@example.com',
        roleId: 1, // 超级管理员角色
        createdAt: new Date().toISOString(),
      },
      {
        id: 2,
        username: 'order_manager',
        password: 'order123',
        name: '订单管理员',
        email: 'order@example.com',
        roleId: 2, // 订单管理员角色
        createdAt: new Date().toISOString(),
      },
    ];
    
    localStorage.setItem('adminUsers', JSON.stringify(defaultAdmins));
    return defaultAdmins;
  }
  
  return JSON.parse(existingAdmins);
};

// 初始化示例订单数据
export const initOrders = () => {
  const existingOrders = localStorage.getItem('orders');
  
  if (!existingOrders) {
    // 生成随机订单ID
    const generateOrderId = () => {
      return 'ORD-' + Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    };
    
    // 生成随机日期（过去30天内）
    const generateRandomDate = () => {
      const now = new Date();
      const pastDays = Math.floor(Math.random() * 30);
      now.setDate(now.getDate() - pastDays);
      return now.toISOString();
    };
    
    // 示例商品列表
    const sampleProducts = [
      { id: 1, title: '智能手机', price: 2999, image: 'https://via.placeholder.com/50' },
      { id: 2, title: '笔记本电脑', price: 5999, image: 'https://via.placeholder.com/50' },
      { id: 3, title: '无线耳机', price: 799, image: 'https://via.placeholder.com/50' },
      { id: 4, title: '智能手表', price: 1299, image: 'https://via.placeholder.com/50' },
      { id: 5, title: '平板电脑', price: 3499, image: 'https://via.placeholder.com/50' },
    ];
    
    // 生成随机订单项
    const generateOrderItems = () => {
      const itemCount = Math.floor(Math.random() * 3) + 1; // 1-3个商品
      const items = [];
      
      for (let i = 0; i < itemCount; i++) {
        const product = sampleProducts[Math.floor(Math.random() * sampleProducts.length)];
        const qty = Math.floor(Math.random() * 3) + 1; // 1-3数量
        
        items.push({
          ...product,
          qty,
        });
      }
      
      return items;
    };
    
    // 生成随机地址
    const generateAddress = (userId) => {
      return {
        fullName: `用户${userId}`,
        email: `user${userId}@example.com`,
        address: '示例街道123号',
        address2: '示例小区',
        state: '示例省',
        country: '中国',
        zip: '100000',
      };
    };
    
    // 生成示例订单
    const generateOrders = (count) => {
      const orders = [];
      const statuses = ['处理中', '已发货', '已完成', '已取消'];
      
      for (let i = 0; i < count; i++) {
        const userId = Math.floor(Math.random() * 10) + 1; // 用户ID 1-10
        const items = generateOrderItems();
        const subtotal = items.reduce((sum, item) => sum + (item.price * item.qty), 0);
        const shipping = 10; // 固定运费
        
        orders.push({
          orderId: generateOrderId(),
          userId,
          date: generateRandomDate(),
          items,
          shippingAddress: generateAddress(userId),
          paymentMethod: Math.random() > 0.5 ? 'credit' : 'other',
          subtotal,
          shipping,
          totalAmount: subtotal + shipping,
          status: statuses[Math.floor(Math.random() * statuses.length)],
        });
      }
      
      return orders;
    };
    
    const defaultOrders = generateOrders(20); // 生成20个示例订单
    localStorage.setItem('orders', JSON.stringify(defaultOrders));
    return defaultOrders;
  }
  
  return JSON.parse(existingOrders);
};

// 初始化所有数据
export const initAllData = () => {
  const roles = initRoles();
  const adminUsers = initAdminUsers();
  const orders = initOrders();
  
  return { roles, adminUsers, orders };
};

export default initAllData;